package com.olympus.hermes.gateway.filter;

import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import org.springframework.web.util.UriComponents;
import org.springframework.web.util.UriComponentsBuilder;

import java.net.URI;

/**
 * @author Mickey
 * @since 2020.09.20
 */
public class HeaderWriterFilter {

    private HeaderWriterFilter() {

    }

    private static class LazyLoader {
        private static final WebFilter INSTANCE = (ServerWebExchange serverWebExchange, WebFilterChain chain) -> {
            ServerHttpRequest serverHttpRequest = serverWebExchange.getRequest();
            String path = serverHttpRequest.getURI().toString();
            UriComponents build = UriComponentsBuilder.fromHttpUrl(path)
                    .encode()
                    .build();
            URI uri = build.toUri();
            serverHttpRequest
                    .mutate()
                    .uri(uri)
                    .header("request_id", serverHttpRequest.getId())
                    .build();
            serverWebExchange = serverWebExchange.mutate().request(serverHttpRequest).build();
            return chain.filter(serverWebExchange);
        };
    }

    public static final WebFilter getInstance() {
        return LazyLoader.INSTANCE;
    }

}

